import initServerInstance from '../server/initServerInstance';
import { TASK_TYPES } from '../common/constants';

const CHANGE_MAP = {
	day: 'd',
	minute: 'm',
	year: 'y',
	week: 'w',
};

if (require.main === module) {
	(async () => {
		const server = await initServerInstance({
			loggerConfig: {
				name: 'upgrade',
				alwaysCreate: true,
			},
		});

		for await (const record of server.app.model.Job.find()) {
			for (const type of TASK_TYPES) {
				const settings = record[`${type}Settings`];
				if (!settings) continue;
				if (Array.isArray(settings)) {
					record[`${type}Settings`] = settings.map(x => {
						if (!x) return x;
						if (x.interval.unit === 'month') {
							x.interval.unit = 'd';
							x.interval.num = x.interval.num * 30;
						} else {
							x.interval.unit = CHANGE_MAP[x.interval.unit] || x.interval.unit;
						}
						return x;
					});
				} else {
					if (settings.interval.unit === 'month') {
						settings.interval.unit = 'd';
						settings.interval.num = settings.interval.num * 30;
					} else {
						settings.interval.unit =
							CHANGE_MAP[settings.interval.unit] || settings.interval.unit;
					}
				}
			}
			await record.save().catch(error => console.log(error));
		}

		await server.app.model.Task.updateMany(
			{ 'taskSettings.interval.unit': 'day' },
			{ $set: { 'taskSettings.interval.unit': 'd' } }
		).catch(error => console.log(error));
		await server.app.model.Task.updateMany(
			{ 'taskSettings.interval.unit': 'minute' },
			{ $set: { 'taskSettings.interval.unit': 'm' } }
		).catch(error => console.log(error));
		await server.app.model.Task.updateMany(
			{ 'taskSettings.interval.unit': 'year' },
			{ $set: { 'taskSettings.interval.unit': 'y' } }
		).catch(error => console.log(error));
		await server.app.model.Task.updateMany(
			{ 'taskSettings.interval.unit': 'week' },
			{ $set: { 'taskSettings.interval.unit': 'w' } }
		).catch(error => console.log(error));
		for await (const record of server.app.model.Task.find({
			'taskSettings.interval.unit': 'month',
		})) {
			record.taskSettings.interval.num *= 30;
			record.taskSettings.interval.unit = 'd';
			await record.save().catch(error => console.log(error));
		}

		process.exit();
	})();
}
